import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

// const tokenKey = 'myToken'
const state = {
  // token: localStorage.getItem(tokenKey) || ''
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    // 1. 改 state
    state.token = data
    // 2. 为了避免刷新丢失数据, 持久化
    // localStorage.setItem(tokenKey, data)
    setToken(data)
  },
  removeToken(state) {
    state.token = ''
    // 同时清理持久化数据
    removeToken()
  },
  setUserInfo(state, data) {
    state.userInfo = data
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  // 异步只能写在 action
  async login(store, data) {
    const res = await login(data)
    // console.log(res)
    // console.log('成功登录后的逻辑')
    // 发送完请求利用 mutation 存 state
    store.commit('setToken', res)
    // 主动介入token失效校验条件一, 需要记录登录成功时间
    localStorage.setItem('loginTime', Date.now())
  },

  async getUserInfo(store) {
    const res = await getUserInfo()
    const data = await getUserDetailById(res.userId)
    // console.log(res)
    store.commit('setUserInfo', { ...res, ...data })
  },
  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
    // 还要重置路由避免高权限退出低权限登录时的残留
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
